using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using API;
using CoreGraphics;
using Foundation;
using Masonry;
using MyExtensions;

using UIKit;

namespace mb.iOS
{
    public class MySimpleTableView : UITableView
    {
        public Func<MySimpleTableView, int, string> MyGetCell;
        public Func<MySimpleTableView, int> MyRowsInSection;
        public Action<MySimpleTableView, int> MyRowSelected;

        public MySimpleTableView() : base()
        {
            Source = new MySource();
        }

        class MySource : UITableViewSource
        {
            public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                var owner = tableView as MySimpleTableView;
                owner.MyRowSelected?.Invoke(owner, indexPath.Row);
            }
            public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
            {
                var owner = tableView as MySimpleTableView;
                var cell = new UITableViewCell(UITableViewCellStyle.Default, "");
                cell.TextLabel.Text = owner.MyGetCell(owner, indexPath.Row);
                return cell;
            }

            public override nint RowsInSection(UITableView tableview, nint section)
            {
                var owner = tableview as MySimpleTableView;
                return owner.MyRowsInSection(owner);
            }
        }
    }

    public class DevServerViewController : UIViewController
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();

        IServerProber serverProber;
        Dictionary < string, (string url, int port) > servers = new Dictionary < string, (string, int) > ();
        List<string> serverList = new List<string>();
        public Action<string, string, int> OnSelect;
        MySimpleTableView serverTableView;

        public DevServerViewController()
        {
            serverProber = mb.ServiceLocator.Instance.Get<IServerProber>();
            serverProber.SetPort(App.AssetServerURI.Item2 + 1);
            serverProber.Refresh();
            serverProber.onNewServer += (name, ip, port) =>
            {
                // logger.Log("found server", name, ip, port, System.Threading.Thread.CurrentThread.ManagedThreadId);
                this.InvokeOnMainThread(() =>
                {

                    if (servers.ContainsKey(name)) return;
                    servers.Add(name, (ip, port));
                    serverList.Add(name);
                    serverList.Sort();
                    serverTableView.ReloadData();
                });
            };

            ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
        }

        public override void ViewDidLoad()
        {
            View.BackgroundColor = UIColor.Black.ColorWithAlpha(0.5f);

            var btn = new UIButton();
            btn.SetParent(View);
            btn.MakeConstraints(m => { m.Edges.EqualTo(View); });
            btn.TouchUpInside += (s, e) =>
            {
                DismissViewController(true, null);
            };

            serverTableView = new MySimpleTableView()
            {
                // BackgroundColor = UIColor.Blue,
                MyRowsInSection = (tv) => serverList.Count,
                    MyGetCell = (tv, row) => serverList[row],
                    MyRowSelected = (tv, row) =>
                    {
                        var name = serverList[row];
                        var info = servers[name];
                        OnSelect(name, info.url, info.port);
                    },
            };
            serverTableView.SetParent(View);
            serverTableView.MakeConstraints(m =>
            {
                m.Center.EqualTo(View);
                m.Width.EqualTo(View).MultipliedBy(0.8f);
                m.Height.EqualTo(View).MultipliedBy(0.5f);
            });
        }
    }
}